package dmsxl.dandiaozhan;

import java.util.*;

/**
 * Author: Zhang Dongwei
 * Date: 2023/9/26 21:02
 */
public class ddz2_496 {
    public static void main(String[] args) {
        int[] nums1 = {4, 1, 2};
        int[] nums2 = {1, 3, 4, 2};
        System.out.println(Arrays.toString(nextGreaterElement(nums1, nums2)));
    }

    //    自己写的，暴力算法，效果还行
    public static int[] nextGreaterElement1(int[] nums1, int[] nums2) {
        int len = nums1.length;
        int[] res = new int[len];
        for (int i = 0; i < len; i++) {
            int pos = 0;
            while (nums2[pos] != nums1[i]) {
                pos++;
            }
            res[i] = -1;
            for (int j = pos + 1; j < nums2.length; j++) {
                if (nums2[j] > nums1[i]) {
                    res[i] = nums2[j];
                    break;
                }
            }
        }
        return res;
    }

    //    解答，单调栈
    public static int[] nextGreaterElement2(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        Arrays.fill(res, -1);
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], i);
        }
        Deque<Integer> stack = new LinkedList<>();
        for (int i = 0; i < nums2.length; i++) {
            while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]) {
                int temp = nums2[stack.peek()];
                if (map.containsKey(temp)) {
                    res[map.get(temp)] = nums2[i];
                }
                stack.pop();
            }
            stack.push(i);
        }
        return res;
    }

    public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        Arrays.fill(res, -1);
        Deque<Integer> stack = new LinkedList<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++){
            map.put(nums1[i], i);
        }
        stack.push(0);
        for (int i = 1; i < nums2.length; i++){
            if (nums2[i] <= nums2[stack.peek()]){
                stack.push(i);
            }else {
                while (!stack.isEmpty() && nums2[i] > nums2[stack.peek()]){
                    if (map.containsKey(nums2[stack.peek()])){
                        res[map.get(nums2[stack.peek()])] = nums2[i];
                    }
                    stack.pop();
                }
                stack.push(i);
            }
        }
        return res;
    }
}
